package com.lzj.servlet;

import com.lzj.dao.UserDao;
import com.lzj.dao.impl.UserDaoImpl;
import com.lzj.entity.Address;
import com.lzj.entity.User;
import com.lzj.entity.UserInfomation;
import com.lzj.service.impl.UserServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * <p>
 *
 * </p>
 *
 * @autor:lzj
 * @date:2021/12/2
 */
public class Register extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String username=req.getParameter("user_name");
        String password=req.getParameter("pwd");
        String cpwd=req.getParameter("cpwd");
        String email=req.getParameter("email");
        if(!password.equals(cpwd)){
            req.setAttribute("msg", "两次输入的密码不同，请重新输入");
            req.getRequestDispatcher("/register.jsp").forward(req,resp);
        }else{
            UserServiceImpl userService = new UserServiceImpl();
            UserDao userDao = new UserDaoImpl();
            userService.setUserDao(userDao);
            User user = userService.queryUserUsername(username);
            if(user==null){
                user=new User(username,password,email);
                int result = userService.addUser(user);
                if(result>0){
                    req.setAttribute("msg", "注册成功，请转到登录页面");
                    User use = userService.queryUserUsername(username);//重新查询用户信息
                    UserInfomation userInfomation = new UserInfomation(username,use.getId());//往用户信息表内导入基本信息
                    int resul = userService.addUserInf(userInfomation);
                    Address address=new Address(use.getId());
                    userService.addAddress(address);
                    req.getRequestDispatcher("/register.jsp").forward(req,resp);
                }else{
                    req.setAttribute("msg","注册失败");
                    req.getRequestDispatcher("/register.jsp").forward(req,resp);
                }
            }else{
                req.setAttribute("msg", "存在相同的用户名，请重新输入");
                req.getRequestDispatcher("/register.jsp").forward(req,resp);
            }
        }


    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }
}
